package cn.hpclub.server.controller.admin.product;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.controller.admin.BaseAdminController;
import cn.hpclub.server.model.product.ProductOrder;
import cn.hpclub.server.service.AccountService;
import cn.hpclub.server.service.product.ProductOrderService;
import cn.hpclub.server.util.ExcelLargeDataUtils;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.QueryHelper;
import cn.hpclub.server.util.SystemConfigUtil;

public class ProductorderController extends BaseAdminController<ProductOrder> {
    private static final String STATUS = "status";
    private static final String MESSAGE = "message";
    private static final String URL = "url";
    private static final String IS_EXPORT = "isExport";
    private static final String QUERY_DATE_FORMAT = "yyyy-MM-dd";
    private static final String END_DATE = "end_date";
    private static final String START_DATE = "start_date";
    private static Logger logger = LoggerFactory.getLogger(ProductorderController.class);
    private static final String ORG_ID = "org_id";

    /**
     * @Title:list
     * @Description:商品订单列表+导出 void
     */
    public void list() {
        ConcurrentHashMap<String, String> searchInfo = getSearchFilter();

        //String sqlSelect = ProductOrderService.service.getSqlSelect();
        //String sqlFilter = ProductOrderService.service.getSqlFilter(searchInfo);
//        QueryHelper helper = ProductOrderService.service.listQueryHelper(searchInfo);
        //从快照读取，不要再实时查询
        QueryHelper helper = ProductOrderService.service.listSnapshotQueryHelper(searchInfo);
        String sqlSelect = helper.getSelect();
        String sqlFilter = helper.getSqlExceptSelect();
        logger.info("ProductorderController list sql  :" + sqlSelect + sqlFilter);
        if (isExportData()) {
            export(sqlSelect, sqlFilter);
        } else {
            setAttrs(searchInfo);
            query(sqlSelect, sqlFilter);
        }
    }

    /**
     * @return ConcurrentHashMap<String,String>
     * @Title: getSearchFilter
     * @Description:获取查询条件
     */
    private ConcurrentHashMap<String, String> getSearchFilter() {
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        int adminId = InterfaceUtil.getAdminId();
        int userRoleType = AccountService.service.getUserRoleType(adminId);
        logger.debug("userRoleType=" + userRoleType);
        // if(userRoleType == Constant.ROLE_TYPE_SUPPLIER_ADMIN){
        // // 角色类型为供应商管理角色时，只能查看由该帐号创建的商品的订单
        // searchInfo.put("creator", String.valueOf(adminId));
        // } else{
        // 其他角色根据机构关系限制数据
        searchInfo.put(ORG_ID, String.valueOf(InterfaceUtil.getOrgId()));
        // }
        setQueryTime(searchInfo);
        if (null == searchInfo.get("order_status")) {
            searchInfo.put("order_status", "10");//默认成功的
        }
        return searchInfo;
    }

    /**
     * @param searchInfo:查询参数列表
     * @Title: setQueryTime
     * @Description:设置查询时间
     */
    private void setQueryTime(ConcurrentHashMap<String, String> searchInfo) {
        if (searchInfo.get(START_DATE) == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.DATE, 1);
            SimpleDateFormat sdf = new SimpleDateFormat(QUERY_DATE_FORMAT);
            String startDate = sdf.format(calendar.getTime());
            searchInfo.put(START_DATE, startDate);
        }
        if (searchInfo.get(END_DATE) == null) {
            SimpleDateFormat sdf = new SimpleDateFormat(QUERY_DATE_FORMAT);
            String startDate = sdf.format(new Date());
            searchInfo.put(END_DATE, startDate);
        }
    }

    /**
     * @param isExport:
     * @return boolean
     * @Title: isExportData
     * @Description:是否输出数据
     */
    private boolean isExportData() {
        logger.debug("isExport=" + getPara(IS_EXPORT));
        return "1".equals(getPara(IS_EXPORT));
    }

    /**
     * @param sqlSelect:SQL查询列表
     * @param sqlFilter:SQL查询条件语句
     * @Title: query
     * @Description:订单查询
     */
    private void query(String sqlSelect, String sqlFilter) {
        findByPageForSearch(sqlSelect, sqlFilter);
        render("/admin/product_order_list.tpl");
    }

    /**
     * @param select:SQL查询列表
     * @param sqlExceptSelect:SQL查询条件语句
     * @Title: export
     * @Description:数据导出
     */
    private void export(String select, String sqlExceptSelect) {
        final String[] headers = new String[]{"订单编号", "订单状态", "商品名称", "商品属性", "商品单价", "IMEI", "销售人员姓名", "销售人员身份", "销售人员手机号 ", "销售员工号",
                "销售员销渠道名称", "销售员渠道编码", "客户手机号", "销售时间", "所属地市", "合约编码", "合约信息", "渠道类型", "区县", "是否客户经理"};
        final String[] columns = new String[]{"OrderId", "OrderStatus", "ProductName", "ProductSkuTitle", "product_price", "IMEI",
                "SalesName", "member_type", "SalesTel", "emp_code", "DisplayName", "NumCode", "CustomerTel", "CreateTime", "CityName",
                "ContractId", "ContractInfo", "class_name", "areaName", "is_accounts_manager"};
        String fileName = generateFileName();
        String filePath = getFilePath(fileName);
        JSONObject jo = null;
        try {
            String sql = select + sqlExceptSelect;
            String url = ExcelLargeDataUtils.exportData(headers, columns, sql, fileName, filePath);
            jo = createDownloadSuccessJSONObject(url);
        } catch (IOException e) {
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    /**
     * @param e:异常对象
     * @return JSONObject
     * @Title: createDownloadErrorJSONObject
     * @Description:创建导出失败JSON对象
     */
    private JSONObject createDownloadErrorJSONObject(IOException e) {
        JSONObject jo = new JSONObject();
        jo.put(STATUS, 0);
        jo.put(MESSAGE, "导出失败：" + e.getMessage());
        return jo;
    }

    /**
     * @param exportFileUrl:导出文件URL，供浏览器下载
     * @return JSONObject
     * @Title: createDownloadSuccessJSONObject
     * @Description:创建导出成功SON对象
     */
    private JSONObject createDownloadSuccessJSONObject(String exportFileUrl) {
        JSONObject jo = new JSONObject();
        jo.put(STATUS, 1);
        jo.put(MESSAGE, "导出成功，点击下载");
        jo.put(URL, exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }

    /**
     * @return String:文件名
     * @Title: generateFileName
     * @Description:获取文件名，根据日期创建导出文件名
     */
    private String generateFileName() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "商品订单" + curTime + ".xlsx";
        return fileName;
    }

    /**
     * @param name:文件名
     * @return String
     * @Title: getFilePath
     * @Description:获取保存文件路径
     */
    private String getFilePath(String fileName) {
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + fileName);
        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        if (!StringUtils.isEmpty(fileDir)) {
            filePath = String.format("%s/file/%s", fileDir, fileName);
        }
        logger.debug("filePath = " + fileDir);
        return filePath;
    }
}
